﻿using AutoMapper;
using IOA.MES.Common;
using IOA.MES.DataAccess.Entity;
using IOA.MES.DataAccess.Enum;
using IOA.MES.DataAccess.VModel;
using IOA.Utils;
using System;
using System.Collections.Generic;
using System.Linq;

namespace IOA.MES.Business
{
    /// <summary>
    /// 过站管理（错误代码：104001）
    /// </summary>
    public class ViaSiteConfigMgr
    {
        private MESContext mesDb = new MESContext("MES");

        /// <summary>
        /// 获取过站配置
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <param name="workOrderNo">工单号</param>
        /// <returns>过站配置</returns>
        public VViaSiteConfig GetConfig(string orderNo = "", string workOrderNo = "")
        {
            VViaSiteConfig model = null;
            if (!string.IsNullOrWhiteSpace(workOrderNo))
            {
                var workOrder = mesDb.WorkOrders.AsNoTracking().FirstOrDefault(_ => _.WorkOrderNo == workOrderNo && _.Valid);
                if (workOrder == null)
                {
                    return null;
                }
                var orderConfigModel = Mapper.Map<VViaSiteConfig>(mesDb.ViaSiteConfigs.AsNoTracking().FirstOrDefault(_ => _.OrderNo == workOrder.OrderNo && _.WorkOrderNo == "" && _.Valid));
                if (orderConfigModel != null)
                {
                    orderConfigModel.ConfigModel = string.IsNullOrWhiteSpace(orderConfigModel.Config) ? null : JsonUtils.Deserialize<ViaSiteConfigModel>(orderConfigModel.Config);
                }
                model = Mapper.Map<VViaSiteConfig>(mesDb.ViaSiteConfigs.AsNoTracking().FirstOrDefault(_ => _.WorkOrderNo == workOrderNo && _.OrderNo == "" && _.Valid));
                if (model == null)
                {
                    if (orderConfigModel != null)
                    {
                        model = orderConfigModel;
                    }
                }
                else
                {
                    model.ConfigModel = string.IsNullOrWhiteSpace(model.Config) ? null : JsonUtils.Deserialize<ViaSiteConfigModel>(model.Config);
                    if (orderConfigModel != null && orderConfigModel.ConfigModel != null)
                    {
                        model.ConfigModel = model.ConfigModel ?? orderConfigModel.ConfigModel;
                        model.ConfigModel.Framing = model.ConfigModel.Framing ?? orderConfigModel.ConfigModel.Framing;
                        model.ConfigModel.IVUpload = model.ConfigModel.IVUpload ?? orderConfigModel.ConfigModel.IVUpload;
                        model.ConfigModel.QTime = model.ConfigModel.QTime ?? orderConfigModel.ConfigModel.QTime;
                        model.ConfigModel.ViaSites = model.ConfigModel.ViaSites ?? orderConfigModel.ConfigModel.ViaSites;
                    }
                }
            }
            else if (!string.IsNullOrWhiteSpace(orderNo))
            {
                model = Mapper.Map<VViaSiteConfig>(mesDb.ViaSiteConfigs.AsNoTracking().FirstOrDefault(_ => _.OrderNo == orderNo && _.WorkOrderNo == "" && _.Valid));
                if (model != null)
                {
                    model.ConfigModel = string.IsNullOrWhiteSpace(model.Config) ? null : JsonUtils.Deserialize<ViaSiteConfigModel>(model.Config);
                }
            }
            else
            {
                model = Mapper.Map<VViaSiteConfig>(mesDb.ViaSiteConfigs.AsNoTracking().FirstOrDefault(_ => _.OrderNo == "" && _.WorkOrderNo == "" && _.Valid));
                if (model != null)
                {
                    model.ConfigModel = string.IsNullOrWhiteSpace(model.Config) ? null : JsonUtils.Deserialize<ViaSiteConfigModel>(model.Config);
                }
            }

            return model;
        }

        /// <summary>
        /// 查询订单工艺配置
        /// </summary>
        /// <param name="orderNo">订单号</param>
        /// <returns>配置列表</returns>
        public List<VViaSiteConfig> QueryViaSiteConfigs(int page, int limit, out int total, string orderNo)
        {
            var query = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.Valid && _.WorkOrderNo == "");
            if (!string.IsNullOrWhiteSpace(orderNo))
            {
                query = query.Where(_ => _.OrderNo.Contains(orderNo));
            }
            else
            {
                query = query.Where(_ => _.OrderNo != "");
            }
            total = query.Count();
            query = query.OrderByDescending(_ => _.PkId);
            var entities = limit <= 0 ? query.ToList() : query.Skip((page - 1) * limit).Take(limit).ToList();
            var models = Mapper.Map<List<VViaSiteConfig>>(entities);

            var orderNos = models.Select(_ => _.OrderNo).Where(_ => !string.IsNullOrWhiteSpace(_)).Distinct().ToList();
            var orders = mesDb.Orders.AsNoTracking().Where(_ => _.Valid && orderNos.Contains(_.InnerOrderNo)).ToList();
            models.ForEach(config =>
            {
                var order = orders.FirstOrDefault(_ => string.Equals(_.InnerOrderNo, config.OrderNo, StringComparison.CurrentCultureIgnoreCase));
                config.CustomerCode = order?.CustomerCode;
                config.CustomerName = order?.CustomerName;
            });
            return models;
        }

        /// <summary>
        /// 获取IV温度配置
        /// </summary>
        /// <returns>IV温度配置</returns>
        public VIVTemp GetIVTemp()
        {
            var entity = mesDb.IVTemps.AsNoTracking().FirstOrDefault(_ => _.Valid);
            return Mapper.Map<VIVTemp>(entity);
        }

        /// <summary>
        /// 获取IV温度配置
        /// </summary>
        /// <returns>IV温度配置</returns>
        public void SaveIVTemp(VIVTemp model)
        {
            var entity = mesDb.IVTemps.AsNoTracking().FirstOrDefault(_ => _.Valid);
            if (entity != null)
            {
                mesDb.IVTemps.Attach(entity);
                entity.Valid = false;
                entity.ModifyBy = model.ModifyBy;
                entity.ModifyTime = DateTime.Now;
            }

            model.CreateTime = DateTime.Now;
            mesDb.IVTemps.Add(Mapper.Map<IVTemp>(model));
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 编辑过站列表
        /// </summary>
        /// <param name="model">过站对象</param>
        public void EditViaSites(VViaSiteConfig model)
        {
            if (!string.IsNullOrWhiteSpace(model.WorkOrderNo))
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == model.WorkOrderNo && _.OrderNo == "" && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                if (entities.Any())
                {
                    var configModel = JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config);
                    configModel.ViaSites = model.ConfigModel.ViaSites;
                    configModel.Framing = model.ConfigModel.Framing;
                    var newConfig = new ViaSiteConfig
                    {
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now,
                        WorkOrderNo = model.WorkOrderNo,
                        Config = JsonUtils.Serialize(configModel)
                    };
                    mesDb.ViaSiteConfigs.Add(newConfig);
                }
                else
                {
                    var configModel = new ViaSiteConfigModel
                    {
                        ViaSites = model.ConfigModel.ViaSites,
                        Framing = model.ConfigModel.Framing
                    };
                    var newConfig = new ViaSiteConfig
                    {
                        OrderNo = string.Empty,
                        WorkOrderNo = model.WorkOrderNo,
                        Config = JsonUtils.Serialize(configModel),
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now
                    };
                    mesDb.ViaSiteConfigs.Add(newConfig);
                }
            }
            else if (!string.IsNullOrWhiteSpace(model.OrderNo))
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == "" && _.OrderNo == model.OrderNo && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                if (!entities.Any())
                {
                    throw new MultiLanBizException(0);//订单配置不存在
                }

                var configModel = JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config);
                configModel.ViaSites = model.ConfigModel.ViaSites;
                configModel.Framing = model.ConfigModel.Framing;
                var newConfig = new ViaSiteConfig
                {
                    CreateBy = model.CreateBy,
                    CreateTime = DateTime.Now,
                    OrderNo = model.OrderNo,
                    Config = JsonUtils.Serialize(configModel)
                };
                mesDb.ViaSiteConfigs.Add(newConfig);
            }
            else
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == "" && _.OrderNo == "" && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                var configModel = entities.Any() ? JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config) :
                    new ViaSiteConfigModel();
                configModel.ViaSites = model.ConfigModel.ViaSites;
                configModel.Framing = model.ConfigModel.Framing;
                var newConfig = new ViaSiteConfig
                {
                    CreateBy = model.CreateBy,
                    CreateTime = DateTime.Now,
                    Config = JsonUtils.Serialize(configModel)
                };
                mesDb.ViaSiteConfigs.Add(newConfig);
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 重置工单过站配置
        /// </summary>
        /// <param name="model">配置对象</param>
        public void ResetOrderConfig(VViaSiteConfig model)
        {
            #region 总配置
            var globalConfig = mesDb.ViaSiteConfigs.AsNoTracking().FirstOrDefault(_ => _.OrderNo == "" && _.WorkOrderNo == "" && _.Valid);
            var orderConfig = mesDb.ViaSiteConfigs.AsNoTracking().FirstOrDefault(_ => _.OrderNo == model.OrderNo && _.WorkOrderNo == "" && _.Valid);
            if (orderConfig != null)
            {
                return;
            }
            else if (globalConfig == null)
            {
                throw new MultiLanBizException(104001);
            }

            var order = mesDb.Orders.AsNoTracking().FirstOrDefault(_ => _.Valid && _.InnerOrderNo == model.OrderNo);
            if (order == null)
            {
                return;
            }
            orderConfig = new ViaSiteConfig
            {
                OrderNo = model.OrderNo,
                WorkOrderNo = string.Empty,
                Config = globalConfig.Config,
                CreateBy = model.CreateBy,
                CreateTime = DateTime.Now
            };
            mesDb.ViaSiteConfigs.Add(orderConfig);
            #endregion

            #region 包装/装柜条件配置
            var globalPackConditions = mesDb.PackConditions.AsNoTracking().Where(_ => _.OrderNo == "" && _.WorkOrderNo == "" && _.Valid).ToList();
            var orderPackConditions = mesDb.PackConditions.AsNoTracking().Where(_ => _.OrderNo == model.OrderNo && _.WorkOrderNo == "" && _.Valid).ToList();
            var q1PackCondition = orderPackConditions.FirstOrDefault(_ => _.QLevelCondition == QLevelCondition.Q1);
            var nq1PackCondition = orderPackConditions.FirstOrDefault(_ => _.QLevelCondition == QLevelCondition.NotQ1);
            if (q1PackCondition == null)
            {
                q1PackCondition = Mapper.Map<PackCondition>(Mapper.Map<VPackCondition>(globalPackConditions.FirstOrDefault(_ => _.QLevelCondition == QLevelCondition.Q1)));
                q1PackCondition.PkId = 0;
                q1PackCondition.OrderNo = model.OrderNo;
                q1PackCondition.WorkOrderNo = string.Empty;
                q1PackCondition.CustomerCode = order.CustomerCode;
                q1PackCondition.CustomerName = order.CustomerName;
                q1PackCondition.CreateBy = model.CreateBy;
                q1PackCondition.CreateTime = DateTime.Now;
                q1PackCondition.ModifyBy = 0;
                q1PackCondition.ModifyTime = null;
                mesDb.PackConditions.Add(q1PackCondition);
            }
            if (nq1PackCondition == null)
            {
                nq1PackCondition = Mapper.Map<PackCondition>(Mapper.Map<VPackCondition>(globalPackConditions.FirstOrDefault(_ => _.QLevelCondition == QLevelCondition.NotQ1)));
                nq1PackCondition.PkId = 0;
                nq1PackCondition.OrderNo = model.OrderNo;
                nq1PackCondition.WorkOrderNo = string.Empty;
                nq1PackCondition.CustomerCode = order.CustomerCode;
                nq1PackCondition.CustomerName = order.CustomerName;
                nq1PackCondition.CreateBy = model.CreateBy;
                nq1PackCondition.CreateTime = DateTime.Now;
                nq1PackCondition.ModifyBy = 0;
                nq1PackCondition.ModifyTime = null;
                mesDb.PackConditions.Add(nq1PackCondition);
            }

            var globalCabinetConditions = mesDb.CabinetConditions.AsNoTracking().Where(_ => _.OrderNo == "" && _.WorkOrderNo == "" && _.Valid).ToList();
            var orderCabinetConditions = mesDb.CabinetConditions.AsNoTracking().Where(_ => _.OrderNo == model.OrderNo && _.WorkOrderNo == "" && _.Valid).ToList();
            var q1CabinetCondition = orderCabinetConditions.FirstOrDefault(_ => _.QLevelCondition == QLevelCondition.Q1);
            var nq1CabinetCondition = orderCabinetConditions.FirstOrDefault(_ => _.QLevelCondition == QLevelCondition.NotQ1);
            if (q1CabinetCondition == null)
            {
                q1CabinetCondition = Mapper.Map<CabinetCondition>(Mapper.Map<VCabinetCondition>(globalCabinetConditions.FirstOrDefault(_ => _.QLevelCondition == QLevelCondition.Q1)));
                q1CabinetCondition.PkId = 0;
                q1CabinetCondition.OrderNo = model.OrderNo;
                q1CabinetCondition.WorkOrderNo = string.Empty;
                q1CabinetCondition.CustomerCode = order.CustomerCode;
                q1CabinetCondition.CustomerName = order.CustomerName;
                q1CabinetCondition.CreateBy = model.CreateBy;
                q1CabinetCondition.CreateTime = DateTime.Now;
                q1CabinetCondition.ModifyBy = 0;
                q1CabinetCondition.ModifyTime = null;
                mesDb.CabinetConditions.Add(q1CabinetCondition);
            }
            if (nq1CabinetCondition == null)
            {
                nq1CabinetCondition = Mapper.Map<CabinetCondition>(Mapper.Map<VCabinetCondition>(globalCabinetConditions.FirstOrDefault(_ => _.QLevelCondition == QLevelCondition.NotQ1)));
                nq1CabinetCondition.PkId = 0;
                nq1CabinetCondition.OrderNo = model.OrderNo;
                nq1CabinetCondition.WorkOrderNo = string.Empty;
                nq1CabinetCondition.CustomerCode = order.CustomerCode;
                nq1CabinetCondition.CustomerName = order.CustomerName;
                nq1CabinetCondition.CreateBy = model.CreateBy;
                nq1CabinetCondition.CreateTime = DateTime.Now;
                nq1CabinetCondition.ModifyBy = 0;
                nq1CabinetCondition.ModifyTime = null;
                mesDb.CabinetConditions.Add(nq1CabinetCondition);
            }
            #endregion
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 编辑IV上传配置
        /// </summary>
        /// <param name="model">配置</param>
        public void EditIVUpload(VViaSiteConfig model)
        {
            if (!string.IsNullOrWhiteSpace(model.WorkOrderNo))
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == model.WorkOrderNo && _.OrderNo == "" && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                if (entities.Any())
                {
                    var configModel = JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config);
                    configModel.IVUpload = model.ConfigModel.IVUpload;
                    var newConfig = new ViaSiteConfig
                    {
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now,
                        WorkOrderNo = model.WorkOrderNo,
                        Config = JsonUtils.Serialize(configModel)
                    };
                    mesDb.ViaSiteConfigs.Add(newConfig);
                }
                else
                {
                    var configModel = new ViaSiteConfigModel
                    {
                        IVUpload = model.ConfigModel.IVUpload
                    };
                    var newConfig = new ViaSiteConfig
                    {
                        OrderNo = string.Empty,
                        WorkOrderNo = model.WorkOrderNo,
                        Config = JsonUtils.Serialize(configModel),
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now
                    };
                    mesDb.ViaSiteConfigs.Add(newConfig);
                }
            }
            else if (!string.IsNullOrWhiteSpace(model.OrderNo))
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == "" && _.OrderNo == model.OrderNo && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                if (!entities.Any())
                {
                    throw new MultiLanBizException(0);//订单配置不存在
                }

                var configModel = JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config);
                configModel.IVUpload = model.ConfigModel.IVUpload;
                var newConfig = new ViaSiteConfig
                {
                    CreateBy = model.CreateBy,
                    CreateTime = DateTime.Now,
                    OrderNo = model.OrderNo,
                    Config = JsonUtils.Serialize(configModel)
                };
                mesDb.ViaSiteConfigs.Add(newConfig);
            }
            else
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == "" && _.OrderNo == "" && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                var configModel = entities.Any() ? JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config) :
                    new ViaSiteConfigModel();
                configModel.IVUpload = model.ConfigModel.IVUpload;
                var newConfig = new ViaSiteConfig
                {
                    CreateBy = model.CreateBy,
                    CreateTime = DateTime.Now,
                    Config = JsonUtils.Serialize(configModel)
                };
                mesDb.ViaSiteConfigs.Add(newConfig);
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 编辑QTime配置
        /// </summary>
        /// <param name="model">配置</param>
        public void EditQTime(VViaSiteConfig model)
        {
            if (!string.IsNullOrWhiteSpace(model.WorkOrderNo))
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == model.WorkOrderNo && _.OrderNo == "" && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                if (entities.Any())
                {
                    var configModel = JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config);
                    configModel.QTime = model.ConfigModel.QTime;
                    var newConfig = new ViaSiteConfig
                    {
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now,
                        WorkOrderNo = model.WorkOrderNo,
                        Config = JsonUtils.Serialize(configModel)
                    };
                    mesDb.ViaSiteConfigs.Add(newConfig);
                }
                else
                {
                    var configModel = new ViaSiteConfigModel
                    {
                        QTime = model.ConfigModel.QTime
                    };
                    var newConfig = new ViaSiteConfig
                    {
                        OrderNo = string.Empty,
                        WorkOrderNo = model.WorkOrderNo,
                        Config = JsonUtils.Serialize(configModel),
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now
                    };
                    mesDb.ViaSiteConfigs.Add(newConfig);
                }
            }
            else if (!string.IsNullOrWhiteSpace(model.OrderNo))
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == "" && _.OrderNo == model.OrderNo && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                if (!entities.Any())
                {
                    throw new MultiLanBizException(0);//订单配置不存在
                }

                var configModel = JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config);
                configModel.QTime = model.ConfigModel.QTime;
                var newConfig = new ViaSiteConfig
                {
                    CreateBy = model.CreateBy,
                    CreateTime = DateTime.Now,
                    OrderNo = model.OrderNo,
                    Config = JsonUtils.Serialize(configModel)
                };
                mesDb.ViaSiteConfigs.Add(newConfig);
            }
            else
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == "" && _.OrderNo == "" && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                var configModel = entities.Any() ? JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config) :
                    new ViaSiteConfigModel();
                configModel.QTime = model.ConfigModel.QTime;
                var newConfig = new ViaSiteConfig
                {
                    CreateBy = model.CreateBy,
                    CreateTime = DateTime.Now,
                    Config = JsonUtils.Serialize(configModel)
                };
                mesDb.ViaSiteConfigs.Add(newConfig);
            }
            mesDb.SaveChanges();
        }

        /// <summary>
        /// 保存物料信息卡控
        /// </summary>
        /// <param name="model">配置对象</param>
        public void SaveMaterialInfoControl(VViaSiteConfig model)
        {
            if (!string.IsNullOrWhiteSpace(model.WorkOrderNo))
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == model.WorkOrderNo && _.OrderNo == "" && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                if (entities.Any())
                {
                    var configModel = JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config);
                    configModel.MaterialInfoControl = model.ConfigModel.MaterialInfoControl;
                    var newConfig = new ViaSiteConfig
                    {
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now,
                        WorkOrderNo = model.WorkOrderNo,
                        Config = JsonUtils.Serialize(configModel)
                    };
                    mesDb.ViaSiteConfigs.Add(newConfig);
                }
                else
                {
                    var configModel = new ViaSiteConfigModel
                    {
                        MaterialInfoControl = model.ConfigModel.MaterialInfoControl
                    };
                    var newConfig = new ViaSiteConfig
                    {
                        OrderNo = string.Empty,
                        WorkOrderNo = model.WorkOrderNo,
                        Config = JsonUtils.Serialize(configModel),
                        CreateBy = model.CreateBy,
                        CreateTime = DateTime.Now
                    };
                    mesDb.ViaSiteConfigs.Add(newConfig);
                }
            }
            else if (!string.IsNullOrWhiteSpace(model.OrderNo))
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == "" && _.OrderNo == model.OrderNo && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                if (!entities.Any())
                {
                    throw new MultiLanBizException(0);//订单配置不存在
                }

                var configModel = JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config);
                configModel.MaterialInfoControl = model.ConfigModel.MaterialInfoControl;
                var newConfig = new ViaSiteConfig
                {
                    CreateBy = model.CreateBy,
                    CreateTime = DateTime.Now,
                    OrderNo = model.OrderNo,
                    Config = JsonUtils.Serialize(configModel)
                };
                mesDb.ViaSiteConfigs.Add(newConfig);
            }
            else
            {
                var entities = mesDb.ViaSiteConfigs.AsNoTracking().Where(_ => _.WorkOrderNo == "" && _.OrderNo == "" && _.Valid).OrderByDescending(_ => _.PkId).ToList();
                foreach (var entity in entities)
                {
                    mesDb.ViaSiteConfigs.Attach(entity);
                    entity.Valid = false;
                    entity.ModifyBy = model.CreateBy;
                    entity.ModifyTime = DateTime.Now;
                }

                var configModel = entities.Any() ? JsonUtils.Deserialize<ViaSiteConfigModel>(entities.FirstOrDefault().Config) :
                    new ViaSiteConfigModel();
                configModel.MaterialInfoControl = model.ConfigModel.MaterialInfoControl;
                var newConfig = new ViaSiteConfig
                {
                    CreateBy = model.CreateBy,
                    CreateTime = DateTime.Now,
                    Config = JsonUtils.Serialize(configModel)
                };
                mesDb.ViaSiteConfigs.Add(newConfig);
            }
            mesDb.SaveChanges();
        }
    }
}
